//
//  MyViewController.m
//  BestPurchase
//
//  Created by ZSMAC on 2018/10/9.
//  Copyright © 2018年 张帅. All rights reserved.
//

#import "MyViewController.h"
#import "loginViewController.h"
#import "ZSTheWavesVIew.h"
#import "UserInfoController.h"
#import "MyReleaseController.h"
#import "MyCollectionController.h"
#import "MyCell.h"

#import "UserModel.h"
@interface MyViewController () <UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView * tableView;
@property(nonatomic,strong)NSArray * dataArray;
@property(nonatomic,retain) UIImageView * headerImageView;
@property(nonatomic,retain) UILabel * nameLabel;
@property(nonatomic,retain) UIButton *refreshBtn ;
@property(nonatomic,retain)UserModel * userModel;

@end

@implementation MyViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (!self.navigationController.navigationBarHidden) {
        self.navigationController.navigationBarHidden=YES;
    }
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    BmobUser * user = [BmobUser currentUser];
    if (!user) {
        _tableView.tableHeaderView=[self addLoginView];
    } else {
        _tableView.tableHeaderView=[self headView];
        _tableView.tableFooterView=[self addFootView];
        if (!_headerImageView.image) {
            [self getUserInfo];
        }
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    self.dataArray=@[@"我的发布",@"我的收藏",@"购物车",@"我的资料"];
    [self uiSet];
    [self getUserInfo];
}
- (void)uiSet {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,-StatusBar_Rect.size.height, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.backgroundColor=[UIColor whiteColor];
    _tableView.estimatedSectionFooterHeight=0;
    _tableView.estimatedSectionHeaderHeight=0;
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
   
}
- (UIView *)addFootView {
    UIView * footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 150)];
    UIButton * exitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    exitBtn.frame=CGRectMake(15, 100,SCREEN_WIDTH-30, 44);
    [exitBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    exitBtn.layer.cornerRadius=5;
    exitBtn.layer.masksToBounds=YES;
    exitBtn.layer.borderWidth=0.7;
    exitBtn.layer.borderColor=[themeColor CGColor];
    [exitBtn setTitleColor:themeColor forState:UIControlStateNormal];
    [exitBtn addTarget:self action:@selector(exitBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:exitBtn];
    
    return footView;
}
- (void)getUserInfo {
    BmobUser * user = [BmobUser currentUser];
    BmobQuery   *bquery = [BmobQuery queryWithClassName:@"_User"];
    @WeakObj(self);
    [bquery getObjectInBackgroundWithId:user.objectId block:^(BmobObject *object,NSError *error){
        if (error && user){
            [ZSProgressHUD showDpromptText:@"获取详情失败"];
        } else {
            NSDictionary * dic = [object valueForKey:@"dataDic"];
             selfWeak.userModel = [UserModel mj_objectWithKeyValues:dic];
            [selfWeak setData];
        }
        [selfWeak performSelector:@selector(DelayLoad) withObject:nil afterDelay:2];
    }];
}
- (void)DelayLoad {
    [_refreshBtn.layer removeAnimationForKey:@"RefreshAnimation"];
}
- (void)setData  {
    [MPublicManager sharedPublicManager].userModel = self.userModel;
    NSString * urlStr = self.userModel.headerUrl;
     [_headerImageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"icon-83.5.png"]];
    NSString * nickname=self.userModel.nickname;
    _nameLabel.text=nickname;
}
- (UIView *)addLoginView {
    UIView * bageView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
    bageView.backgroundColor=themeColor;
 
    ZSTheWavesVIew * myView = [[ZSTheWavesVIew alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, bageView.height)];
    myView.speed=0.5;
    myView.backgroundColor=[UIColor clearColor];
    ///外层浪颜色
    myView.outsideWavesLayerColor=[UIColor whiteColor];
    ///里面浪颜色
    myView.insideWavesLayerColor=[[UIColor whiteColor] colorWithAlphaComponent:0.5];
    [myView tartAnimation];
    [bageView addSubview:myView];
    
    
    
    UIButton * LoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    LoginBtn.frame=CGRectMake(bageView.width/2-40, bageView.height/2-20, 80, 40);
    [LoginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [LoginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [LoginBtn addTarget:self action:@selector(pushLoginViewController) forControlEvents:UIControlEventTouchUpInside];
    LoginBtn.layer.cornerRadius=3;
    LoginBtn.layer.masksToBounds=YES;
    LoginBtn.layer.borderColor=[[UIColor whiteColor] CGColor];
    LoginBtn.layer.borderWidth=0.7;
    [bageView addSubview:LoginBtn];
    return bageView;
}
- (UIView *)headView {
    UIView * bageView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
    bageView.backgroundColor=themeColor;
    //头像
    if (_headerImageView==nil) {
        _headerImageView =[[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2-40, bageView.height/2-40, 80, 80)];
    }

    _headerImageView.layer.cornerRadius=40;
    _headerImageView.layer.masksToBounds=YES;
    _headerImageView.layer.borderColor=[[UIColor whiteColor] CGColor];
    _headerImageView.layer.borderWidth=0.8;
    [bageView addSubview:_headerImageView];
    //昵称
    if (_nameLabel==nil) {
        _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, _headerImageView.bottom+10, SCREEN_WIDTH-30, 30)];
    }
    _nameLabel.textAlignment=NSTextAlignmentCenter;
    _nameLabel.textColor=[UIColor whiteColor];
    _nameLabel.font=[UIFont boldSystemFontOfSize:16];
    [bageView addSubview:_nameLabel];
    
    ZSTheWavesVIew * myView = [[ZSTheWavesVIew alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, bageView.height)];
    myView.speed=0.5;
    myView.backgroundColor=[UIColor clearColor];
    ///外层浪颜色
    myView.outsideWavesLayerColor=[UIColor whiteColor];
    ///里面浪颜色
    myView.insideWavesLayerColor=[[UIColor whiteColor] colorWithAlphaComponent:0.5];
    ///开始动画
    [myView tartAnimation];
    [bageView addSubview:myView];
   
    if (!_refreshBtn) {
       _refreshBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _refreshBtn.frame=CGRectMake(SCREEN_WIDTH-40, 30, 25, 25);
        _refreshBtn.backgroundColor=[UIColor clearColor];
        [_refreshBtn setImage:[UIImage imageNamed:@"refresh"] forState:UIControlStateNormal];
        [_refreshBtn addTarget:self action:@selector(refreshBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    }
    
    [bageView addSubview:_refreshBtn];
    
    return bageView;
}
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * identifier = @"identifier";
    MyCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell=[[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    NSArray * imageNames = @[@"商品.png",@"我的收藏.png",@"购物车.png",@"我的资料.png"];
    cell.myTitleLabel.text=self.dataArray[indexPath.row];
    cell.headerImageView.image=[UIImage imageNamed:imageNames[indexPath.row]];
    return cell;
}
#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    BmobUser * user = [BmobUser currentUser];
    if (!user) {
        [ZSProgressHUD showDpromptText:@"请登录"];
        return;
    }
    if (indexPath.row==0) {
        MyReleaseController * releaseVC = [[MyReleaseController alloc] init];
        [self.navigationController pushViewController:releaseVC animated:YES];
    } else if (indexPath.row==1) {
        MyCollectionController *CollectionVc = [[MyCollectionController alloc] init];
        CollectionVc.collections=self.userModel.collections;
        [self.navigationController pushViewController:CollectionVc animated:YES];
    }
    if (indexPath.row==3) {
        UserInfoController * userInfo = [[UserInfoController alloc] init];
        userInfo.headerImage=_headerImageView.image;
        userInfo.nikeName=_nameLabel.text;
        [self.navigationController pushViewController:userInfo animated:YES];
    }
   
}
- (void)pushLoginViewController {
    loginViewController * vc = [[loginViewController alloc] init];
    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:vc];
    UIViewController * currentVC = [MPublicManager sharedPublicManager].currentControllr;
    [currentVC presentViewController:nav animated:YES completion:nil];
}
- (void)exitBtnClick {
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您确定要退出登录吗？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    @WeakObj(self);
    UIAlertAction *determine=[UIAlertAction actionWithTitle:@"退出" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       [BmobUser logout];
        selfWeak.tableView.tableFooterView=nil;
        selfWeak.tableView.tableHeaderView=[selfWeak addLoginView];
    }];
    [alert addAction:cancelAction];
    [alert addAction:determine];
  [self presentViewController:alert animated:YES completion:nil];
    
    [BmobUser logout];
}
- (void)refreshBtnClicked {
    [self RefreshRrotateAnimation];
    [self getUserInfo];
}
#pragma mark 刷新按钮动画
- (void)RefreshRrotateAnimation {
    CABasicAnimation *animation =  [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    //默认是顺时针效果，若将fromValue和toValue的值互换，则为逆时针效果
    animation.fromValue = [NSNumber numberWithFloat:0.f];
    animation.toValue =  [NSNumber numberWithFloat: M_PI *2];
    animation.duration  = 0.5;
    animation.autoreverses = NO;
    animation.fillMode =kCAFillModeForwards;
    animation.repeatCount = MAXFLOAT; //如果这里想设置成一直自旋转，可以设置为MAXFLOAT，否则设置具体的数值则代表执行多少次
    [_refreshBtn.layer addAnimation:animation forKey:@"RefreshAnimation"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
